<template>
  <div class="doctor">
    <!-- 查询表单 -->
    <el-form inline :model="condition" ref="Datarefs">
      <el-form-item label="用户编号">
        <el-input v-model="condition._id" placeholder="请输入用户编号" />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="condition.username" placeholder="请输入昵称" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary">查询</el-button>
        <el-button type="primary" @click="editUserVisible = true">新增会员信息</el-button>
        <el-button type="primary" @click="handleExportFile">导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="users" style="width: 100%" border>
      <el-table-column type="selection" />
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="_id" label="编号" width="250" />
      <el-table-column prop="username" label="用户名" width="130" />
      <el-table-column prop="realName" label="真实姓名" width="130" />
      <el-table-column prop="section" label="所属科室" width="130" />
      <el-table-column prop="phone" label="电话号码" width="130" />
      <el-table-column prop="age" label="年龄" width="70" />
      <el-table-column prop="sex" label="性别" width="70" />
      <el-table-column prop="address" label="地址" width="120" />
      <el-table-column prop="mailbox" label="邮箱" width="170" />
      <el-table-column prop="birthday" label="注册时间" width="190">
        <template #default="scope">
          <span>{{ formatData(scope.row.birthday) }}</span>
        </template>
      </el-table-column>
      <!-- 状态插槽 -->
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-switch :modelValue="scope.row.status" class="ml-2" />
        </template>
      </el-table-column>
      <!-- 编辑插槽 -->
      <el-table-column fixed="right" label="操作" width="160">
        <template #default="scope">
          <el-button type="primary" @click="modify(scope.row)">编辑</el-button>
          <el-button type="danger" @click="Remove(scope.row._id)">删除</el-button>
        </template>
      </el-table-column>


    </el-table>

    <!-- 分页器 -->
    <el-pagination background layout="total, prev, pager, next, sizes, ->,  jumper" :total="total"
      :page-sizes="[2, 3, 5, 10, 20]" @current-change="pageChange" @size-change="sizeChange" />


    <!-- 新增或修改会员的对话框 -->
    <el-dialog v-model="editUserVisible" title="编辑会员">
      <!-- 渲染编辑会员表单 -->
      <edit-user ref="editUserRef" @success="handleSaveSucess"></edit-user>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editUserVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { findMembers, delMembers, addMembersFile } from '../../api/member'
import dayjs from 'dayjs'
import { utils, writeFileXLSX } from 'xlsx'

import { ElMessageBox } from 'element-plus'

import EditUser from './edit-doctor.vue'
// import { tr } from 'element-plus/es/locale'

export default {
  name: 'Doctor',
  components: {
    EditUser,
  },
  data() {
    return {

      // 查询条件
      condition: {},

      //会员数量
      users: [],
      total: 0,
      page: 1,
      pageSize: 10,

      // 编辑对话框的现实隐藏
      editUserVisible: false,
    }
  },

  created() {
    this.findMembers();
  },

  methods: {
    //查询医生
    findDoctor(id) {
      return this.list.filter(id => this.id)
    },
    handleClick() { },
    handleExportFile() { },

    // 查询会员
    async findMembers({ page = 1, pageSize = 30 } = {}) {
      const { list, page: _page, pageSize: _pageSize } = await findMembers({ page, pageSize })
      this.users = [...list]
      this.page = _page,
        this.pageSize = _pageSize,
        this.total = this.users.length
    },

    // 日期格式化
    formatData(datetime) {
      return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
    },

    /* 
      翻页
    */
    pageChange(page) {
      this.findMembers({ page, pageSize: this.pageSize })
    },

    sizeChange(pageSize) {
      this.findMembers({ page: this.page, pageSize })
    },

    // 删除用户
    async Remove(id) {
      console.log(id)
      try {
        await ElMessageBox.confirm(
          '确认删除当前医生信息吗?',
          '删 除',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            center: true,
          }
        )

        // 确认删除
        await delMembers(id)
        // 删除成功。重新渲染
        this.findMembers({ page: this.page, pageSize: this.pageSize })
      } catch (error) {
        console.log(error)
      }
    },

    /**
 * 导出 excel
 */
    handleExportFile() {
      // 将待导出数据转换为 sheet 工作表中要使用到的数据，并生成工作表
      const ws = utils.json_to_sheet(this.users)
      // 创建新工作簿
      const wb = utils.book_new()
      // 将工作表追加到工作簿中
      utils.book_append_sheet(wb, ws, "会员信息")
      // 将内存中的工作簿数据写入文件中
      writeFileXLSX(wb, `user-${new Date().toISOString()}.xlsx`)
    },

    // 保存用户
    async handleSave() {
      try {
        const user = await this.$refs.editUserRef.validate()
        // console.log('user',user)
        // if (user) {
        //   this.editUserVisible = false
        //   addMembersFile(user)
        //   // findMembers()
        // }
      } catch (error) {
        console.log('error:', error)
      }
    },

    // 保存成功
    handleSaveSucess() {
      this.editUserVisible = false
      this.findMembers()
    },

    // 获取用户数据
    // getUserById(id) {
    //   return this.users.find(user => user._id === id)
    // },

    // 编辑用户
    modify(user) {
      this.editUserVisible = true
      this.$nextTick(() => {
        console.log('ref', this.$refs.editUserRef)
        this.$refs.editUserRef.setData(user)
        // findMembers()
      })
    },

    // 修改用户
    // async handleModify(user) {
    //   try {
    //     // 调用 API 方法更新用户数据
    //     const result = await modifyMember(user)
    //     console.log(result, '修改结果')
    //     // 关闭对话框
    //     this.editUserVisible = false
    //     // 重新获取用户数据
    //     this.findMembers()
    //   } catch (error) {
    //     console.log('error:', error)
    //   }
    // }

  },
}
</script>

<style lang="less" >
.el-table .cell {
  text-align: center;
}

.el-dialog {
  width: 500px;
  text-align: center;
  padding-right: 20px;
}
</style>
